#include "tcp_cli.h"

int TcpConnect(TCPClient *p, const char *str, int port) {
	if (NULL == p || NULL == str) {
		return -1;
	}
	struct sockaddr_in tmpsock;
	memcpy((void *)p->strAddr, str, strlen(str));
	p->iPort = port;
	p->CientSocket = socket(AF_INET, SOCK_STREAM, 0);
	tmpsock.sin_port = htons(port);
	tmpsock.sin_addr.s_addr = inet_addr(str);
	tmpsock.sin_family = AF_INET;
	bzero(tmpsock.sin_zero, 8);
	p->LocalAddr = tmpsock;
	int iRet = connect(p->CientSocket, (const struct sockaddr *)&p->LocalAddr, sizeof(struct sockaddr));
	if(iRet<0)
		printf("error connect socker %d errno %d\n",iRet,errno);
	return iRet;
}

int TcpSend(TCPClient *p, char pStr[], int iLen) {
	if (NULL == p || NULL == pStr) {
		return -1;
	}
#ifdef WIN32
	int iRet = send(p->CientSocket, pStr, iLen, 0);
	if (iRet < 0) {
		closesocket(p->CientSocket);
		p->CientSocket = -1;

	}
	return iRet;
#endif
#ifdef linux
int iRet = send(p->CientSocket, pStr, iLen, MSG_DONTWAIT);
	if (iRet < 0) {
		close(p->CientSocket);
		p->CientSocket = -1;

	}
	if(iRet != iLen){
		printf("error socket send %d\n", iRet);
	}
	return iRet;
#endif
}

int TcpRecv(TCPClient *p, char pStr[], int iLen) {
	int iRet = -1;
	int iOffset = 0;
	if (NULL == p || NULL == pStr) {
		return -1;
	}
#ifdef WIN32
	iRet = recv(p->CientSocket, pStr, iLen, 0);
	if (iRet < 0) {
		closesocket(p->CientSocket);
		p->CientSocket = -1;
	}
#endif
#ifdef linux
	iRet = recv(p->CientSocket, pStr + iOffset, iLen, 0);
	printf("%s\n", pStr);
	if (iRet < 0) {
		close(p->CientSocket);
		p->CientSocket = -1;
	}
	if(pStr[iRet + iOffset -4] !='\r' &&pStr[iRet +iOffset -3] != '\n' 
		&&pStr[iRet + iOffset -2] !='\r' &&pStr[iRet +iOffset -1] != '\n')
	{
		iOffset += iRet;
	}
#endif
	return iRet;
}

int TcpClose(TCPClient *p) {
#ifdef WIN32
	p->CientSocket = -1;
	closesocket(p->CientSocket);
	return 0;
#endif
}